<?php

namespace App\Models\Dynamic;

use App\Models\BasicModel;
use App\Models\User;
use Dcat\Admin\Traits\HasDateTimeFormatter;

class Review extends BasicModel
{
	use HasDateTimeFormatter;
    protected $table = 'dynamic_review';


    public function getList($post_id,$uid){
        $list=self::where(['dynamic_id'=>$post_id,'review_id'=>0])->with(['user'=>function($query){
            $query->select(['id','name','avatar']);
        }])->paginate(10);
        foreach ($list as &$item){
            $item->isLike=Likes::where(['user_id'=>$uid,'post_id'=>$item->id,'type'=>3])->first() ? 1 : 0;
            $item['reply']=$this->getChild($item->id,$item->user->name);
        }
        return $list;
    }

    private function getChild($r_id,$name){
        $data=[];
        $review=self::where(['review_id'=>$r_id])->with(['user'=>function($query){
            $query->select(['id','name','avatar']);
        }])->first();
        if($review){
            $review->title=$review->user->name.' 回复 '.$name;
            $data[]=$review;
            $this->getChild($review->id,$review->user->name);
        }
        return $data;
    }


    public function user()
    {
        return $this->hasOne(User::class, 'id', 'user_id');
    }

    public function dynamic()
    {
        return $this->belongsTo(Lists::class, 'dynamic_id', 'id');
    }
}
